﻿$(document).ready(function () {
    $(".select").click(function () {
        var id = $(this).attr('id');
        var link = this;
        var parent = $(link).parents('.item');
        parent.append('<div class="ontop"></div>');
        parent.find('.ontop').html('processing...');
        parent.find('.ontop').animate({ 'opacity': '0.7' }, 200);
        $.ajax({
            url: '/Basket/Add?id=' + id,
            success: function (data) {
                if (data == 'true') {
                    var number = /[0-9]+/;
                    var found = number.exec($(link).text());
                    $(link).text('Add to basket (' + (++found) + ')');
                    parent.find('.ontop').html('Added');
                    setTimeout(function () {
                        parent.find('.ontop').fadeOut(1000,
                        function () { $(this).remove(); })
                    }, 1000);
                } else {
                    alert('Iternal error');
                }
            },
            error: function () {
                alert('Ajax error');
            }
        });
    });

    $(".delete").click(function () {
        var id = $(this).attr('id');
        var link = this;
        $.ajax({
            url: '/Basket/Del?id=' + id,
            success: function (data) {
                if (data <= 0) {
                    $(link).parents('.item').fadeOut(500, function () {
                        $(this).remove();
                        if ($('.item').length == 0) {
                            $('#content').append('<h1>Nothing found for this query</h1>');
                        }
                    });
                } else {
                    $(link).parents('.item').find('.count').addClass('warn').fadeOut(200, function () {
                        $(this).html(data).fadeIn(200).removeClass('warn');
                    });
                }
            },
            error: function () {
                alert('Ajax error');
            }
        });
    });
});